<template>
  <div class="container">
    <el-row>
      <el-col :span="6">
        <el-input
          class="filter-item search"
          placeholder="美容院名称"
          @keyup.enter.native="$refs.table.loadData()"
          v-model="params.search">
          <el-button slot="append" icon="el-icon-search" @click="$refs.table.loadData()"></el-button>
        </el-input>
      </el-col>
      <el-col :span="18" class="text-right">
        <el-button type="primary" @click="onAdd">添加美容院</el-button>
      </el-col>
    </el-row>

    <we-table url="user/beauty" :params="params" ref="table">
      <el-table-column label="美容院名称" width="200" property="nickname"></el-table-column>
      <el-table-column label="美容院管理员账号" width="300" property="username"></el-table-column>
      <el-table-column label="美容院活动链接">
        <template slot-scope="scope" v-if="scope.row.activityId">
          <el-popover
            placement="bottom-end"
            width="160"
            trigger="click">
            <h4 class="qucode-info">请使用微信扫描</h4>
            <qrcode :value="shareUrl + scope.row.activityId" type="img"></qrcode>
            <el-button type="text" slot="reference">{{shareUrl + scope.row.activityId}}</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" property="createTime" width="240"></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="250">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="loadActivity(scope.row.id)">活动</el-button>
          <el-button type="success" size="mini" v-has="0" @click="onResetPass(scope.row)">重置密码</el-button>
          <el-button type="danger" size="mini" v-has="0" @click="onDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </we-table>

    <el-dialog title="添加美容院" :visible.sync="formVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-row>
          <el-form-item label="美容院名称" prop="nickname">
            <el-input v-model="form.nickname" placeholder="美容院名称" maxlength="20"></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="登录账号" prop="username">
            <el-input v-model="form.username" placeholder="登录账号" maxlength="20"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="登录密码" prop="password">
            <el-input type="password" v-model="form.password" placeholder="登录密码" :maxlength="20"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" v-if="resetPassVisible" :visible.sync="resetPassVisible" width="500px">
      <el-form>
        <el-row>
          <el-form-item label="登录密码" prop="resetPass">
            <el-input type="password" v-model="resetPass" placeholder="登录密码" :maxlength="20"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetPassVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitPass" :disabled="resetPass.length < 6">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="美容院活动" v-if="activityDialog" :visible.sync="activityDialog" @close="close" width="60%">

      <el-form :model="myform" :rules="activityRules" ref="myform">
        <el-row :gutter="20">
          <el-col :md="12">
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="myform.name" placeholder="活动名称" :maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="活动时间" prop="activityTime">
              <el-date-picker
                v-model="myform.activityTime"
                type="datetimerange"
                range-separator=" - "
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['09:00:00', '18:00:00']"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :md="8">
            <el-form-item label="分享积分" prop="integralRule">
              <el-input v-model="myform.integralRule" placeholder="分享积分" :maxlength="5"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="活动地点" prop="address">
              <el-input v-model="myform.address" placeholder="活动地点" :maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="myform.phone" placeholder="联系电话" :maxlength="11"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="分享标题" prop="shareTitle">
            <el-input v-model="myform.shareTitle" placeholder="分享标题" :maxlength="50"></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="分享描述" prop="shareContent">
            <el-input type="textarea" v-model="myform.shareContent" placeholder="分享描述" :maxlength="200"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="美容院头像" prop="pic" class="lin-float">
            <multi-file v-model="myform.pic" :limit="1" @validate="handleSuccess"></multi-file>
          </el-form-item>
          <el-form-item label="礼品标题" prop="fileTitleImgId" class="lin-float">
            <multi-file v-model="myform.fileTitleImgId" :limit="1" @validate="$refs['myform'].validateField('fileTitleImgId')"></multi-file>
          </el-form-item>
          <el-form-item label="活动规则" prop="rulesImgId" class="lin-float">
            <multi-file v-model="myform.rulesImgId" :limit="1" @validate="handleSuccess5"></multi-file>
          </el-form-item>
          <el-form-item label="报名成功" prop="saluteImgId" class="lin-float">
            <multi-file v-model="myform.saluteImgId" :limit="1" @validate="handleSuccess6"></multi-file>
          </el-form-item>
          <el-form-item label="已报名" prop="repeatSaluteImgId" class="lin-float">
            <multi-file v-model="myform.repeatSaluteImgId" :limit="1" @validate="handleSuccess7"></multi-file>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="活动申明" prop="statementImgId" class="lin-float">
            <multi-file v-model="myform.statementImgId" :limit="1"></multi-file>
          </el-form-item>
          <el-form-item label="活动视频" prop="activityImgId" class="lin-float">
            <multi-file v-model="myform.activityVideoId" :accept="'video/*'" :limit="1"></multi-file>
          </el-form-item>
          <el-form-item label="礼品视频" prop="activityImgId" class="lin-float">
            <multi-file v-model="myform.fileVideoId" :limit="1" :accept="'video/*'"></multi-file>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="活动图片" prop="activityImgId">
            <multi-file v-model="myform.activityImgId" :limit="5"></multi-file>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="礼品图片" prop="fileImgId">
            <multi-file v-model="myform.fileImgId" :limit="5"></multi-file>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="activityDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitActivity">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Activity from "view/activity"

  export default {
    components: {
      Activity
    },
    data() {
      var _this = this

      function validateIntegral(str) {
        if (Number(str) % 2 == 0) {
          return true
        }
        return false
      }

      var checkIntegral = (rule, value, callback) => {
        setTimeout(() => {
          if (value && !validateIntegral(value)) {
            callback(new Error(rule.message))
          } else {
            callback()
          }
        }, 200)
      }
      var checkUserName = (rule, value, callback) => {
        setTimeout(() => {
          _this.$http.post("/user/findByName/" + value).then(res => {
            if (0 === res.code) {
              if (res.data != null) {
                callback(new Error(rule.message))
              } else {
                callback()
              }
            } else {
              callback(new Error(rule.message))
            }
          })
        }, 200)
      }

      return {
        params: {},
        formVisible: false,
        resetPassVisible: false,
        shareUrl: window.location.origin + '/activityShare.html?id=',
        form: {},
        rules: {
          nickname: [
            {required: true, message: '请输入美容院名称', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
          ],
          username: [
            {required: true, message: '请输入登录账号', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'},
            {validator: checkUserName, message: '帐号已存在', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
          ],
        },
        resetPassRules: {
          resetPass: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
          ]
        },
        resetPass: "",
        toActivity: "",
        myform: {
          activityTime: '',
          pic: ''
        },
        activityRules: {
          name: [
            {required: true, message: '请输入活动名称', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
          ],
          activityTime: [
            {required: true, message: '请选择活动时间', trigger: 'change'},
          ],
          integralRule: [
            {required: true, message: '请输入分享积分', trigger: 'blur'},
            {validator: checkIntegral, message: '请输入2的倍数', trigger: 'blur'}
          ],
          address: [
            {required: true, message: '请输入活动地址', trigger: 'blur'}
          ],
          pic: [{required: true, message: '请上传美容院头像', trigger: 'change'}],
          fileTitleImgId: [{required: true, message: '请上传礼品标题', trigger: 'change'}],
          rulesImgId: [{required: true, message: '请上传活动规则', trigger: 'change'}],
          saluteImgId: [{required: true, message: '请上传报名图片', trigger: 'change'}],
          repeatSaluteImgId: [{required: true, message: '请上传重复报名图片', trigger: 'change'}],
          phone: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号！'}
          ],
          shareTitle: [
            {required: true, message: '请输入分享标题', trigger: 'blur'}
          ],
          shareContent: [
            {required: true, message: '请输入分享标题', trigger: 'blur'}
          ],
          introduces: [
            {required: true, message: '请输入学院简介', trigger: 'blur'}
          ],
        },
        activityDialog: false,
        uploadUrl: "",
        beautyId: null,
        array: []
      }
    },
    methods: {
      onSubmitPass() {
        let {id, username} = this.toActivity
        const from = {
          id: id,
          name: username,
          resetPass: this.resetPass
        };

        this.$http.post("/user/resetPass", from).then(res => {
          if (0 === res.code) {
            this.$notify.success({
              title: '成功',
              message: '密码重置成功！'
            });
            this.resetPassVisible = false;
          } else {
            this.$notify.error({
              title: '失败',
              message: res.msg
            });
          }
        })
      },
      onResetPass(row) {
        this.toActivity = row
        this.resetPass = ""
        this.resetPassVisible = true
      },
      /**
       * 添加美容院
       */
      onAdd() {
        this.formVisible = true
      },
      /**
       * 提交美容院
       */
      onSubmit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$http.post('/user/beauty', this.form).then((res) => {
              if (0 === res.code) {
                this.$notify.success({
                  title: '成功',
                  message: '保存成功！'
                });
                this.formVisible = false
                this.$refs.table.loadData()
              } else {
                this.$notify.error({
                  title: '失败',
                  message: res.msg
                });
              }
            })
          }
        });
      },
      /**
       * 删除选中美容院
       */
      onDel(row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete('/user?id=' + row.id).then((res) => {
            if (0 === res.code) {
              this.$notify.success({
                title: '成功',
                message: '删除成功！'
              });
              this.formVisible = false
              this.$refs.table.loadData()
            } else {
              this.$notify.error({
                title: '失败',
                message: res.msg
              });
            }
          })
        }).catch(() => {
        })
      },
      /**
       * 提交活动
       */
      onSubmitActivity() {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            const activityTime = this.myform.activityTime
            if (activityTime && activityTime.length === 2) {
              this.myform.startTime = activityTime[0]
              this.myform.endTime = activityTime[1];
            }
            this.myform.pic = typeof this.myform.pic == 'object' ? this.myform.pic.join() : this.myform.pic
            this.myform.activityImgId = typeof this.myform.activityImgId == 'object' ? this.myform.activityImgId.join(",") : this.myform.activityImgId
            this.myform.fileImgId = typeof this.myform.fileImgId == 'object' ? this.myform.fileImgId.join(",") : this.myform.fileImgId
            this.myform.rulesImgId = typeof this.myform.rulesImgId == 'object' ? this.myform.rulesImgId.join() : this.myform.rulesImgId
            this.myform.activityVideoId = typeof this.myform.activityVideoId == 'object' ? this.myform.activityVideoId.join() : this.myform.activityVideoId
            this.myform.fileVideoId = typeof this.myform.fileVideoId == 'object' ? this.myform.fileVideoId.join() : this.myform.fileVideoId
            this.myform.saluteImgId = typeof this.myform.saluteImgId == 'object' ? this.myform.saluteImgId.join() : this.myform.saluteImgId
            this.myform.repeatSaluteImgId = typeof this.myform.repeatSaluteImgId == 'object' ? this.myform.repeatSaluteImgId.join() : this.myform.repeatSaluteImgId
            this.myform.statementImgId = typeof this.myform.statementImgId == 'object' ? this.myform.statementImgId.join() : this.myform.statementImgId
            this.myform.creater = this.beautyId
            this.$http.post('/activity', this.myform).then((res) => {
              if (0 === res.code) {
                this.$notify.success({
                  title: '成功',
                  message: '保存成功！'
                });
                this.activityDialog = false
                this.$refs.table.loadData()
              } else {
                this.$notify.error({
                  title: '失败',
                  message: res.msg
                });
              }
            })
          }
        });
      },
      validate() {
        this.$refs['myform'].validateField('pic')
      },
      loadActivity(beautyId) {
        this.beautyId = beautyId
        this.$http.get("/activity/now/" + this.beautyId).then(res => {
          if (res.code === 0 && res.data != null) {
            this.myform = res.data
            this.myform.activityTime = []
          } else {
            this.myform = {
              activityTime: []
            }
          }
          this.myform.pic = this.filetIds(this.myform.pic)
          this.myform.activityVideoId = this.filetIds(this.myform.activityVideoId)
          this.myform.fileVideoId = this.filetIds(this.myform.fileVideoId)
          this.myform.saluteImgId = this.filetIds(this.myform.saluteImgId)
          this.myform.repeatSaluteImgId = this.filetIds(this.myform.repeatSaluteImgId)
          this.myform.statementImgId = this.filetIds(this.myform.statementImgId)
          this.myform.activityImgId = this.myform.activityImgId ? this.myform.activityImgId.split(",") : []
          this.myform.fileImgId = this.myform.fileImgId ? this.myform.fileImgId.split(",") : []
          this.myform.rulesImgId = this.filetIds(this.myform.rulesImgId)
          if (this.myform.startTime && this.myform.endTime) {
            this.myform.activityTime.push(this.myform.startTime)
            this.myform.activityTime.push(this.myform.endTime)
          }
          this.activityDialog = true
        })
      },
      disabledDate(time) {
        return time < new Date()
      },
      handleSuccess() {
        this.$refs['myform'].validateField('pic')
      },
      handleSuccess5() {
        this.$refs['myform'].validateField('rulesImgId')
      },
      handleSuccess6() {
        this.$refs['myform'].validateField('saluteImgId')
      },
      handleSuccess7() {
        this.$refs['myform'].validateField('repeatSaluteImgId')
      },
      filetIds(val) {
        let array = []
        if (val) {
          array.push(val)
        }
        return array
      }
      ,
      close() {
        this.$refs.table.loadData()
      }
    }
  }
</script>
<style lang="sass" scoped>
  .qucode-info
    text-align: center
    margin: 10px 0
</style>
<style>
  .el-form-item__label {
    float: inherit !important;
  }

  .lin-float {
    float: left;
    width: 19%;
  }
</style>
